//
//  LPFStatusDAL.swift
//  WeiBo
//
//  Created by mac on 16/4/28.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

class LPFStatusDAL: NSObject {
    
    //获取微博首页数据
    class func getHomeStatus(since_id: Int64, max_id: Int64, callback:(array: [[String: AnyObject]])->()){
        
        
        let result = checkoutCacheStatus(since_id, max_id: max_id)
        
        if result.count == 0{
            
            LPFNetworkTools.sharedTools.loadStatus(LPFUserAccountTools.sharedTools.accessToken!, since_id: since_id, max_id: max_id, callback: { (response, error) -> () in
                
                
                if error != nil{
                    print(error)
                    callback(array: [])
                    return
                }
                // 判断我们的得到的数据是否存在 而且是否是一个数组
                guard let array = response?["statuses"] as? [[String: AnyObject]] else{
                    print("返回的数据不是一个数组")
                    callback(array: [])
                    return
                }
                print("网络数据")
                callback(array: array)
                //缓存到本地
                LPFStatusDAL.saveStatus(array)
                
            })
            
        }else{
            
            print("本地数据")
            callback(array: result)
        }
        
    }
    
    // 供外界查询本地数据
    class func checkoutCacheStatus(since_id: Int64, max_id: Int64) ->[[String: AnyObject]]{
        
        let uid = LPFUserAccountTools.sharedTools.userAccount!.uid!
        var sql = "SELECT status FROM T_Status WHERE userId = \(uid)"
        //下拉刷新
        if since_id > 0{
            sql += " AND statusId > \(since_id)"
        }
        //上啦加载更多
        if max_id > 0{
            sql += " AND statusId < \(max_id)"
        }
        
        sql += " ORDER BY statusId DESC LIMIT 20"
        
        var tempArray:[[String: AnyObject]] = [[String: AnyObject]]()
        
        SQLManager.sharedTools.queue.inDatabase { (db) -> Void in
            do{
                let res = try! db.executeQuery(sql)
//                print(res)
                while res.next(){
                    let status = res.dataForColumn("status")
                    let dic = try! NSJSONSerialization.JSONObjectWithData(status, options: []) as! [String: AnyObject]
                    tempArray.append(dic)
                }
                
            }catch{
                print(error)
            }
            
        }
        return tempArray
    }
    
    
    // 提供一个保存从网络加载回来的数据方法
    class func saveStatus(array:[[String: AnyObject]]) {
        
        let uid = LPFUserAccountTools.sharedTools.userAccount!.uid!
        
        let sql = "INSERT OR REPLACE INTO T_Status (statusId,status,userId) VALUES (?,?,?)"
        
        
        SQLManager.sharedTools.queue.inTransaction { (db, rollback) -> Void in
            do {
                for dic in array{
                    let statusId = dic["id"] as! NSNumber
//                    print("结果\(statusId)")
                    let status = try! NSJSONSerialization.dataWithJSONObject(dic, options: [])
                    
                    try db.executeUpdate(sql, statusId, status, uid)
                }
                
            }catch{
                print(error)
                rollback.memory = true
            }
        }
        
        
        
    }
}
